package com.test.utils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * Created by ZZF on 2017/7/4.
 */
public class BaseUtils {
    /**
     * 从配置文件中读取上下限值
     *
     * @return
     */
    public static Map<String, String> inputConfig() {


        Properties prop = new Properties();
        Map<String, String> propertiesMap = new HashMap<>();
        try {
            //读取属性文件a.properties ..\newSSHM\src\main\resources\
            ClassLoader classLoader = BaseUtils.class.getClassLoader();
            URL resource = classLoader.getResource("config.properties");
            String path = resource.getPath();
           /// System.out.println(path);

            InputStream in = new BufferedInputStream(new FileInputStream(path));
            prop.load(in);     ///加载属性列表
            Iterator<String> it = prop.stringPropertyNames().iterator();
            while (it.hasNext()) {
                String key = it.next();
                propertiesMap.put(key, prop.getProperty(key)); //把属性值用键值对再次封装

            }
            in.close();

        } catch (Exception e) {
            System.out.println(e);
        }


        return propertiesMap;
    }

    /**
     * 把一些object类型转化为BigDecimal
     *
     * @param value
     * @return
     */
    public static BigDecimal getBigDecimal(Object value) {
        BigDecimal ret = null;
        if (value != null) {
            if (value instanceof BigDecimal) {
                ret = (BigDecimal) value;
            } else if (value instanceof String) {
                ret = new BigDecimal((String) value);
            } else if (value instanceof BigInteger) {
                ret = new BigDecimal((BigInteger) value);
            } else if (value instanceof Number) {
                ret = new BigDecimal(((Number) value).doubleValue());
            } else {
                throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
            }
        }
        return ret;
    }

    //初始化验证
    public static BigDecimal initBigDecimal(BigDecimal numb) {
        if (numb == null) {

            BigDecimal newNumb = new BigDecimal(0.00);
            return newNumb;
        }
        DecimalFormat df = new DecimalFormat("#.00");

        return getBigDecimal( df.format(numb));
    }

    public static Double formatDouble(double initDouble){

        DecimalFormat df = new DecimalFormat("0.00");//格式化小数

        String s = df.format(initDouble);//返回的是String类型

        return  Double.valueOf(s);

    }

    //偏正值
    public static int deviation(){

        int deviation = (int)(5 + Math.random() * (10 - 5));

        return deviation;
    }

}
